<?php

class PersonalController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$rurl = '/personal';
			$this->_redirect('/login?rurl='.$rurl);
		}
		$tel = $auth->getUserName();
		$this->view->tel = $tel;
    }

    public function topupAction()
    {
		$auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$rurl = '/personal/topup';
			$this->_redirect('/login?rurl='.$rurl);
		}
		$userid = $auth->getUserId();
        $rest = new Application_Model_Rest();
		$req = $this->getRequest();
		if($req->isGet()){
			$res = $rest->getUserTopupRole(-1);
			$res_info = $rest->getUser();
			$this->view->res_info = $res_info;
			$this->view->res = $res;
		}
		if($req->isXMLHttpRequest()){
			$roleid = $req->getPost('roleid');
			$tag = $req->getPost('tag');
			$roleItem = $rest->getUserTopupRole($roleid);
			if(empty($roleItem)){
				echo json_encode(array("msg"=>'errorToDetails'));
				exit;
			}
			$expenditure = $roleItem[0]->amount;
			$res_tran = $rest->postUserTopup(1,$expenditure,'余额充值',$roleid);//type 1充值
			if(empty($res_tran)){
				echo json_encode(array("msg"=>'errorToDetails'));
				exit;
			}
			if(!empty($res_tran)&&is_object($res_tran)&&property_exists($res_tran,'topupid')){
				//1.create transactionId
				//2.wxparams
				if($tag == 'weixin'){
					$action = 'prepay&platform=weixin';
					$topupid = $res_tran->topupid;
					$res = $rest->putUserTopup($action,$topupid);// create transactionid
					if(empty($res)){
						echo json_encode(array("msg"=>'errorToDetails'));
						exit;
					}
					$transactionId = $res->transaction_id;
					//fixed
					$wxAPI = new Application_Model_WXApi();
					$price = $expenditure;
					$inserttime = $roleItem[0]->inserttime;
					$wxparams = $wxAPI->genereateTopupWXPayParams($transactionId, $price,$inserttime);
					if(empty($wxparams)){
						echo json_encode(array("msg"=>"errorToDetails"));
						exit;
					}
					echo json_encode(array('msg'=>'success','wxparams'=>$wxparams,'topupid'=>$topupid,'uid'=>$userid,'transactionId'=>$transactionId,'price'=>$price));
					exit;
				}else{
					$action = 'prepay&platform=taobao';
					$topupid = $res_tran->topupid;
					$res = $rest->putUserTopup($action,$topupid);// create transactionid
					if(empty($res)){
						echo json_encode(array("msg"=>'errorToDetails'));
						exit;
					}
					$transactionId = $res->transaction_id;
					$inserttime = $roleItem[0]->inserttime;
					echo json_encode(array('msg'=>'success','transactionId'=>$transactionId,'inserttime'=>$inserttime));
					exit;
				}
			}
		}
    }

    public function topupdetailAction()
    {
       $auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$rurl = '/personal/topup';
			$this->_redirect('/login?rurl='.$rurl);
		}
        $rest = new Application_Model_Rest();
		$res = $rest->getUserTopup(-1);
		$this->view->res = $res;
		$res_info = $rest->getUser();
		$this->view->res_info = $res_info;
    }

    public function wxqueryAction()
    {
       include_once(APPLICATION_PATH ."/../library/WxPayPubHelper/WxPayPubHelper.php");
		$req = $this->getRequest();
		if($req->isGet()){
			$type = $req->get('type');
			if(!empty($type)&&$type=='kk'){
				$trade_no = $req->get('trade_no');
				$topupid = $req->get('topupid');
				if(empty($trade_no)||empty($topupid)){
					$this->_redirect('/error');
				}else{
					$out_trade_no = $trade_no;
					$orderQuery = new OrderQuery_pub();
					$orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
					//获取订单查询结果
					$orderQueryResult = $orderQuery->getResult();
					if ($orderQueryResult["return_code"] == "FAIL") {
						$this->_redirect('/error');
					}
					elseif($orderQueryResult["result_code"] == "FAIL"){
						$this->_redirect('/error');
					}
					else{
						$trade_state = $orderQueryResult['trade_state'];//交易状态
						$openid = $orderQueryResult['openid'];     //openid
						$is_subscribe = $orderQueryResult['is_subscribe'];//是否关注公众号
						$trade_type = $orderQueryResult['trade_type'];//交易类型
						$bank_type = $orderQueryResult['bank_type'];//付款银行
						$total_fee = $orderQueryResult['total_fee'];//总金额
						$fee_type = $orderQueryResult['fee_type'];//货币种类
						$transaction_id = $orderQueryResult['transaction_id'];//微信支付订单号
						$out_trade_no = $orderQueryResult['out_trade_no'];//商户订单号
						$time_end = $orderQueryResult['time_end'];//支付完成时间
						
						$rest = new Application_Model_Rest();
						$action = 'pay&transactionId='.$trade_no.'&platformId='.$transaction_id;
						$res_pay = $rest->putUserTopup($action,$topupid);
						$this->_redirect('/personal/topupdetail');
					}	
				}
			}else{
				$this->_redirect('/error');
			}
		}
    }

    public function zfbpayAction()
    {
        // $req=$this->getRequest();
		// if($req->isGet()){
			// $roleid = $req->get('roleid');
			// $transactionId = $req->get('transactionId');
			// $inserttime = $req->get('inserttime');
			// if(empty($roleid)||empty($transactionId)){
				// $this->_redirect('/error');
			// }
			// $rest = new Application_Model_Rest();
			// $res = $rest->getUserOrderTransaction($transactionId);
			// $transaction_status = $res->transaction_status;
			// $has_paid = $res->order_has_paid;
			// $price = $res->price;
			// $ordercode = $res->ordercode;
			// if($has_paid != 0 || $transaction_status != 1){
				// echo '<script type="text/javascript">alert("亲，您已支付成功，请回到微信点击订单查询");window.close();</script>';
				// exit;
			// }
			// if($price<=0){
				// $this->_redirect('/error');
			// }
			// $this->view->price = $price;
			// $this->view->ordercode = $ordercode;
			// $this->view->transactionId = $transactionId;
			// $this->view->orderid = $orderid;
			// $this->view->inserttime = $inserttime;
				
		// }

		// if($req->isPost()){
			// $transactionId = $req->getPost('transactionId');
			// $rest = new Application_Model_Rest();
			// $res = $rest->getUserOrderTransaction($transactionId);
			// $transaction_status = $res->transaction_status;
			// $has_paid = $res->order_has_paid;
			// if($has_paid == 1 && $transaction_status == 2){
				// echo json_encode(array("msg"=>"has_paid"));
				// exit;
			// }else{
				// echo json_encode(array("msg"=>"notPay"));
				// exit;
			// }
		// 
    }

    public function topuppayAction()
    {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        $req = $this->getRequest();
		$rest = new Application_Model_Rest();
		if($req->isGet()){
			$oid = $req->get('oid');
			$auth = new Application_Model_Auth();
			if(!$auth->isLoggedIn()){
				$rurl = '/order/status?oid='.$oid;
				$this->_redirect('/login?rurl='.$rurl);
			}
			$details = $rest->getUserOrderDetails($oid);
			if(empty($details)){
				$this->_redirect('/order/status?oid='.$oid);
			}
			$custprice = $details->custprice;
			$res_postUserTopup = $rest->postUserTopup(2,$custprice,'订单消费',$oid);//type 2消费
			if(!empty($res_postUserTopup)){
				$topupid = $res_postUserTopup->topupid;
				$action = 'orderpay&platform=weixin&orderid='.$oid;
				$res_putUserTopup = $rest->putUserTopup($action,$topupid);
				if(!empty($res_putUserTopup)&&$res_putUserTopup->has_paid==1){
					$this->_redirect('/order/success?oid='.$oid);
				}else{
					$this->_redirect('/order/status?oid='.$oid);
				}
			}
			else{
				$this->_redirect('/order/status?oid='.$oid);
			}
		}
    }

    public function rechargeAction()
    {
        // action body
		$req = $this->getRequest();
		$auth = new Application_Model_Auth();
		$rest = new Application_Model_Rest();
		if($req->isGet()){
			 $topupRoleList = $rest->getUserTopupRole(-1);
			 $this->view->topupRoleList = $topupRoleList;
		}
		
		
		if($req->isPost() && $req->isXMLHttpRequest()){
			$tel = $req->getPost('tel');
			$roleId = $req->getPost('roleId');
			if(!$auth->isLoggedIn()){
				echo json_encode(array('msg'=>'needLogin'));
				exit;
			}
			$userid=$auth->getUserId();
			if(empty($tel) || empty($roleId)){
				echo json_encode(array('msg'=>'dataError'));
				exit;
			}
			$roleItem = $rest->getUserTopupRole($roleId);
			if(empty($roleItem)){
				echo json_encode(array("msg"=>'dataError'));
				exit;
			}
			$expenditure = $roleItem[0]->amount;
			$res_tran = $rest->postUserTopup(1,$expenditure,'余额充值',$roleId);//type 1充值
			if(empty($res_tran)){
				echo json_encode(array("msg"=>'errorToDetails'));
				exit;
			}
			if(!empty($res_tran)&&is_object($res_tran)&&property_exists($res_tran,'topupid')){
				//1.create transactionId
				//2.wxparams
				$tag = 'weixin';
				if($tag == 'weixin'){
					$action = 'prepay&platform=weixin';
					$topupid = $res_tran->topupid;
					$res = $rest->putUserTopup($action,$topupid);// create transactionid
					if(empty($res)){
						echo json_encode(array("msg"=>'errorToDetails'));
						exit;
					}
					$transactionId = $res->transaction_id;
					//fixed
					$wxAPI = new Application_Model_WXApi();
					$price = $expenditure;
					$inserttime = $roleItem[0]->inserttime;
					$wxparams = $wxAPI->genereateTopupWXPayParams($transactionId, $price,$inserttime);
					if(empty($wxparams)){
						echo json_encode(array("msg"=>"errorToDetails"));
						exit;
					}
					echo json_encode(array('msg'=>'success','wxparams'=>$wxparams,'topupid'=>$topupid,'uid'=>$userid,'transactionId'=>$transactionId,'price'=>$price));
					exit;
				}
			}
		}
    }

    public function validateAction()
    {
        // action body
		$req = $this->getRequest();
	   if($req->isGet()){
		   $tel = $req->get('tel');
		   $roleId = $req->get('roleId');
		   if(empty($tel) || empty($roleId)){
			   $this->_redirect('/recharge');
		   }
		   $this->view->tel = $tel;
		   $this->view->roleId = $roleId;
	   }
	   //login
	   if($req->isPost() && $req->isXMLHttpRequest()){
		   		$captcha = $req->getPost('captcha');
				$phone = $req->getPost('phone');
				$code = $req->getPost('code');
				$verify = $req->getPost('verify');
				$rurl = $req->getPost('rurl');
				if(empty($captcha)||empty($phone)){
					echo json_encode(array('msg'=>'paraNull'));
					exit;
				}
				$auth = new Application_Model_Auth();
				if(!$auth->authorise($phone,$captcha,$verify,$code)) {
					echo json_encode(array('msg'=>'captchaWrong'));
					exit;
				}
				echo json_encode(array('msg'=>'success','rurl'=>$rurl));
				exit;
	   }
    }


}















